﻿using Company.Core.Attributes;
using Company.Core.Helpers;
using Company.Core.Models;
using Company.Logger;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Company.Hardware.Detector.Simulation
{
    /// <summary>
    /// 平板探测器具体实现子类
    /// </summary>
    [ExposedService(Lifetime.Singleton, typeof(IDetector), AutoInitialize = true)]
    public class DetectorSimulation : DetectorBase
    {
        private bool _isGrabbing = false;

        public override event Action<DetectorImage> OnTrigger;

        public override bool DoClose()
        {
            if (Initialized)
            {
                // 关闭设备

                _isGrabbing = false;
                return true;
            }

            return false;
        }

        public override bool DoInitialize()
        {
            // 连接设备
            Thread.Sleep(500);

            return true;
        }

        public override bool DoGrab()
        {
            if (!_isGrabbing)
            {
                _isGrabbing = true;
                Task.Run(async () =>
                {
                    while (_isGrabbing)
                    {
                        // FPD一般返回的是16位灰度图，所以这里用 ushort 表达单个像素大小。
                        var unmanagedArray = new UnmanagedArray2D<ushort>(Config.Width, Config.Height);
                        var bitmap = (Bitmap)Image.FromFile(Path.Combine("data", Config.SimulationImage)); // 模拟设备返回的照片
                        if (bitmap.Width != Config.Width || bitmap.Height != Config.Height)
                        {
                            Application.Current.Dispatcher.Invoke(() =>
                            {
                                Logs.LogError(new Exception("系统设置中平板探测器分辨率与实际分辨率不一致"));
                            });
                        }

                        var bitmapData = bitmap.LockBits(new Rectangle(System.Drawing.Point.Empty, bitmap.Size)
                                         , System.Drawing.Imaging.ImageLockMode.ReadWrite
                                         , bitmap.PixelFormat);
                        MemoryHelper.CopyMemory(unmanagedArray.IntPtr, bitmapData.Scan0, unmanagedArray.Size);
                        bitmap.UnlockBits(bitmapData);
                        RaiseTriggerEvent(new DetectorImage(unmanagedArray));
                        await Task.Delay(100);
                    }
                });
            }

            return true;
        }

        private void RaiseTriggerEvent(DetectorImage image)
        {
            OnTrigger?.Invoke(image);
        }

    }
}
